package com.wang.vedio.fragment;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.fragment.NewLazyFragment;
import com.vondear.rxui.view.dialog.RxDialogJBSureCancel;
import com.wang.vedio.MainActivity2;
import com.wang.vedio.R;
import com.wang.vedio.net.SharedHelper;
import com.wang.vedio.net.entity.BaseBean;
import com.wang.vedio.net.entity.LoginBean;
import com.wang.vedio.net.rxjava.HttpMethods;
import com.wang.vedio.net.subscribers.ProgressSubscriber;
import com.wang.vedio.net.subscribers.SubscriberOnNextListener;
import com.wang.vedio.player.BussessHeZuoActivity;
import com.wang.vedio.player.CollectVedioListActivity;
import com.wang.vedio.player.InviteFriendActivity;
import com.wang.vedio.player.LookVedioNoteActivity;
import com.wang.vedio.player.PasswordActivity;
import com.wang.vedio.player.VipActivity;
import com.wang.vedio.utils.GlideEngine;
import com.wang.vedio.utils.StringUtils;
import com.wang.vedio.view.StatusBarUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 描述：线索发现
 */
public class PersonalCenterFragment extends NewLazyFragment {
    Unbinder unbinder;


    @BindView(R.id.titleLinear)
    View titleLinear;

    @BindView(R.id.person_username)
    TextView person_username;

    @BindView(R.id.sygycs)
    TextView sygycs;

    @BindView(R.id.jryqrs)
    TextView jryqrs;

    @BindView(R.id.jryqjl)
    TextView jryqjl;

    @BindView(R.id.img1)
    ImageView img1;

    @BindView(R.id.headPic)
    ImageView headPic;

    @BindView(R.id.gyjlLinear)
    View gyjlLinear;
    @BindView(R.id.scypLinear)
    View scypLinear;
    @BindView(R.id.qlhcLinear)
    View qlhcLinear;
    @BindView(R.id.swhzLinear)
    View swhzLinear;
    @BindView(R.id.bbgxLinear)
    View bbgxLinear;
    @BindView(R.id.setPassword)
    View setPassword;




    @BindView(R.id.signLinear)
    View signLinear;

    @BindView(R.id.inviteImg)
    View inviteImg;

    @BindView(R.id.vipTv)
    ImageView vipTv;

    @BindView(R.id.zyInfo)
    TextView zyInfo;

    @BindView(R.id.bgImg)
    ImageView bgImg;

    @BindView(R.id.qianDaoBtn)
    View qianDaoBtn;
    @BindView(R.id.hasQianDaoTiShi)
    View hasQianDaoTiShi;



    @Override
    protected int getContentViewId() {
        return R.layout.gyss_fragment_personalcenter_layout;
    }

    @Override
    protected void initView(View view) {
        unbinder = ButterKnife.bind(this, view);
        titleLinear.setPadding(0, StatusBarUtil.getStatusBarHeight(mContext), 0, 0);
    }


    @Override
    protected void initData() {
        person_username.setText(SharedHelper.readValueByKeyForString(mContext, "ncName"));
        sygycs.setText("0");
        jryqrs.setText("0人");
        jryqjl.setText("0元");
    }

    private void getData() {
        
        SubscriberOnNextListener<BaseBean<LoginBean>> onNextListener = baseBean -> {
            
            sygycs.setText(baseBean.getData().getTodayLookNumber() + "次");
            jryqrs.setText(baseBean.getData().getJryqrs() + "人");
            jryqjl.setText(baseBean.getData().getJryqsyMoney() + "元");
            person_username.setText(baseBean.getData().getNcName());
            zyInfo.setText(baseBean.getData().getAddUserAccount());
            Glide.with(headPic)
                    .load(HttpMethods.BASE_URL + baseBean.getData().getHeadPic())
                    .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(90))))
                    .into(headPic);

            String fmImg = baseBean.getData().getAddUserName();

            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.icon_renwu_bg)//图片加载出来前，显示的图片
                    .fallback(R.mipmap.icon_renwu_bg) //url为空的时候,显示的图片
                    .error(R.mipmap.icon_renwu_bg);//图片加载失败后，显示的图片
            Glide.with(mContext).load(HttpMethods.BASE_URL+fmImg).apply(options).into(bgImg);

            if (StringUtils.isEmpty(baseBean.getData().getVipEndTime())) {
                img1.setVisibility(View.GONE);
            } else {
                img1.setVisibility(View.VISIBLE);
            }
        };
        Map<String, Object> params = new HashMap<>();
        params.put("memberId", SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().getPersonCenterInfo(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    private void updateUser(String userName) {
        
        SubscriberOnNextListener<BaseBean<LoginBean>> onNextListener = baseBean -> {
            
            person_username.setText(userName);
            RxToast.normal("修改成功！");
        };
        Map<String, Object> params = new HashMap<>();
        params.put("id", SharedHelper.readId(mContext));
        params.put("ncName", userName);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), new Gson().toJson(params));
        HttpMethods.getInstance().updateMember(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    private void uploadImg(String path) {
        
        SubscriberOnNextListener<BaseBean<LoginBean>> onNextListener = baseBean -> {
            
            Glide.with(headPic)
                    .load(HttpMethods.BASE_URL + baseBean.getData().getHeadPic())
                    .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(90))))
                    .into(headPic);
            RxToast.normal("修改成功！");
        };
        File file = new File(path);
        MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型，类型为八位字节流
        RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("id", SharedHelper.readId(mContext))//添加表单数据
                .addFormDataPart("headPic", file.getName(), requestBody)//文件名,请求体里的文件
                .build();
        HttpMethods.getInstance().uploadMemberHeadPic(new ProgressSubscriber<>(onNextListener, mContext, false), multipartBody);
    }


    @Override
    public void onResume() {
        super.onResume();
        setCouldClick(((MainActivity2)getActivity()).isCanSign());
        getData();
    }

    private void initRxDialog() {
        RxDialogJBSureCancel rxDialogEditSureCancel = new RxDialogJBSureCancel(mContext);
        rxDialogEditSureCancel.getTitleView().setText("用户名");
        rxDialogEditSureCancel.getEditText().setHint("用户名");
        rxDialogEditSureCancel.getEditText().setText(person_username.getText().toString());
        rxDialogEditSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogEditSureCancel.dismiss();
            }
        });
        rxDialogEditSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rxDialogEditSureCancel.dismiss();
                if (StringUtils.isEmpty(rxDialogEditSureCancel.getEditText().getText().toString())) {
                    RxToast.normal("请输入用户名");
                    return;
                }
                updateUser(rxDialogEditSureCancel.getEditText().getText().toString());
            }
        });
        rxDialogEditSureCancel.show();
    }

    @OnClick({R.id.qianDaoBtn, R.id.vipTv, R.id.person_username, R.id.headPic,R.id.gyjlLinear,R.id.scypLinear,R.id.qlhcLinear,R.id.swhzLinear,R.id.bbgxLinear,R.id.inviteImg,R.id.signLinear,R.id.setPassword})
    public void onClick(View v) {
        if(v.getId() == R.id.qianDaoBtn){
            Bundle bundle = new Bundle();
            bundle.putInt("type",0);
            RxActivityTool.skipActivity(mContext, InviteFriendActivity.class,bundle);
        } else if (v.getId() == R.id.person_username) {
            initRxDialog();
        } else if (v.getId() == R.id.vipTv) {
            RxActivityTool.skipActivity(mContext, VipActivity.class);
        } else if (v.getId() == R.id.headPic) {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .setPictureWindowAnimationStyle(new PictureWindowAnimationStyle())// 自定义相册启动退出动画
                    .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项   参考Demo MainActivity中代码
                    //   .isOriginalImageControl(cb_original.isChecked())// 是否显示原图控制按钮，如果用户勾选了 压缩、裁剪功能将会失效
                    .isWeChatStyle(true)// 是否开启微信图片选择风格，此开关开启了才可使用微信主题！！！
                    .isAndroidQTransform(true)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && enableCrop(false);有效
                    .maxSelectNum(1)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(3)// 每行显示个数 int
                    .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .queryMaxFileSize(50)// 只查多少M以内的图片、视频、音频  单位M
                    //   .querySpecifiedFormatSuffix(PictureMimeType.ofPNG())// 查询指定后缀格式资源
                    // .cameraFileName("test.png") // 重命名拍照文件名、注意这个只在使用相机时可以使用
                    //  .renameCompressFile("test.png")// 重命名压缩文件名、 注意这个不要重复，只适用于单张图压缩使用
                    //  .renameCropFileName("test.png")// 重命名裁剪文件名、 注意这个不要重复，只适用于单张图裁剪使用
                    //   .isSingleDirectReturn(false)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .isGif(true)// 是否显示gif图片 true or false
                    //   .compressSavePath(getPath())//压缩图片保存地址
                    .openClickSound(false)// 是否开启点击声音 true or false
                    .cutOutQuality(90)// 裁剪输出质量 默认100
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }else if(v.getId() == R.id.gyjlLinear){
            RxActivityTool.skipActivity(mContext, LookVedioNoteActivity.class);
        }else if(v.getId() == R.id.scypLinear){
            RxActivityTool.skipActivity(mContext, CollectVedioListActivity.class);
        }else if(v.getId() == R.id.qlhcLinear){
            RxToast.normal("清除成功！");
        }else if(v.getId() == R.id.swhzLinear){
            RxActivityTool.skipActivity(mContext, BussessHeZuoActivity.class);
        }else if(v.getId() == R.id.signLinear){
            Bundle bundle = new Bundle();
            bundle.putInt("type",0);
            RxActivityTool.skipActivity(mContext, InviteFriendActivity.class,bundle);
        }else if(v.getId() == R.id.inviteImg){
            Bundle bundle = new Bundle();
            bundle.putInt("type",1);
            RxActivityTool.skipActivity(mContext, InviteFriendActivity.class,bundle);
        }else if(v.getId() == R.id.setPassword){
            Bundle bundle = new Bundle();
            bundle.putInt("type",-1);
            RxActivityTool.skipActivity(mContext, PasswordActivity.class,bundle);
        }
    }

    public void setCouldClick(boolean show){
        hasQianDaoTiShi.setVisibility(show?View.VISIBLE:View.GONE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10:
                // 图片选择结果回调
                if (!PictureSelector.obtainMultipleResult(data).isEmpty()) {
                    String locationPath = PictureSelector.obtainMultipleResult(data).get(0).getPath();
                    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        locationPath = PictureSelector.obtainMultipleResult(data).get(0).getAndroidQToPath();
                    }
//                    RequestOptions options = new RequestOptions()
//                            .placeholder(R.mipmap.ic_paizhao_img)//图片加载出来前，显示的图片
//                            .fallback(R.mipmap.ic_paizhao_img) //url为空的时候,显示的图片
//                            .error(R.mipmap.ic_paizhao_img);//图片加载失败后，显示的图片
//                    Glide.with(mContext).load(locationPath).apply(options).into(headPic);
                    Glide.with(headPic)
                            .load(locationPath)
                            .apply(RequestOptions.bitmapTransform(new MultiTransformation<>(new CenterCrop(), new RoundedCorners(90))))
                            .into(headPic);
                    uploadImg(locationPath);
                }
                break;

        }
    }
}
